#encoding:utf-8
from flask import (abort, Blueprint, flash, redirect, render_template, request,
                   url_for)
from flask.ext.login import login_required

from app.ext import mongo
from bson.objectid import ObjectId

app = Blueprint('backend', __name__)
ALLOWED_EXTENSIONS = set(['txt', 'pdf', 'png', 'jpg', 'jpeg', 'gif'])


@app.route('/postplayer', methods=['GET', 'POST'])
@login_required
def postplayer():
    if request.method == 'GET':
        id = request.args.get('id')
        if id:
           player = mongo.db.player.find_one({'_id': ObjectId(id)})
           return render_template('post_player.html', player=player)
        return render_template('post_player.html')

    else:

        name = request.form.get('name')
        display_name = request.form.get('display_name')
        value = request.form.get('listvalue')
        photo = request.files['file']

        if not name or not display_name or not value:
            flash(u'不能为空')
            return render_template('post_player.html')

        player = mongo.db.player.find_one({'name': name})
        if player:
            player['display_name'] = display_name
            player['game_value'] = int(value)

        else:
            player = {
            'name':name,
            'display_name':display_name,
            'game_value':int(value)

            }

        player_id = mongo.db.player.save(player)
        if not photo is None:
            mongo.save_file(str(player_id)+'.png', photo)
        print 'saved'
        flash(u'保存成功')


        return render_template('post_player.html')

@app.route('/players/<display_name>', methods=['GET'])
@app.route('/players', methods=['GET'])
@login_required
def players(display_name=None):
    players = []
    if display_name:
        players = mongo.db.player.find({'display_name': display_name})
    else:
       players = mongo.db.player.find().sort([("game_value",-1)])

    return render_template('players.html', players=players)

@app.route('/player/del/<id>', methods=['GET'])
@login_required
def delete_player(id):
    if not id:
        return render_template('404.html')
    mongo.db.player.remove({'_id': ObjectId(id)})
    flash(u'removed')
    return redirect(url_for('backend.players'))

